# 导入必要的库
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
from sklearn.tree import DecisionTreeRegressor, plot_tree

# 设置显示选项，显示所有列
pd.set_option('display.max_columns', None)

# 定义数据路径
data_path = os.path.join('..', 'EVChargingUsageAnalysis-master', 'Data', 'Cleaned_EVUsage_Data.csv')

# 加载数据
df = pd.read_csv(data_path, low_memory=False)

# 打印数据的前几行，获取数据信息和描述统计
print(df.head())
print(df.info())
print(df.describe(include='all'))

# 将数据信息和描述统计保存到文件
with open('data_info.txt', 'w') as fp:
    fp.write(str(df.info()))
    fp.write(str(df.describe(include='all')))

# 数据预处理：将交易日期转换为日期时间格式并设为索引
df['Transaction Date (Pacific Time)'] = pd.to_datetime(df['Transaction Date (Pacific Time)'])
df.set_index('Transaction Date (Pacific Time)', inplace=True)

# 绘制每周总充电耗能趋势图
plt.figure(figsize=(12, 6))
plt.subplot(2, 1, 1)
monthly_energy_sum = df['Energy (kWh)'].resample('W').sum()
monthly_energy_sum.plot()
plt.title('Weekly Total Energy Consumption')
plt.xlabel('Date')
plt.ylabel('Energy Consumption (kWh)')
plt.grid(True)
plt.legend(['Total Energy'], loc='upper right')

# 绘制每周平均充电耗能趋势图
plt.subplot(2, 1, 2)
monthly_energy_mean = df['Energy (kWh)'].resample('W').mean()
monthly_energy_mean.plot()
plt.title('Weekly Average Energy Consumption')
plt.xlabel('Date')
plt.ylabel('Energy Consumption (kWh)')
plt.grid(True)
plt.legend(['Average Energy'], loc='upper right')

# 保存图表到文件
plt.savefig('Weekly_Energy_Analyse.png')
plt.subplots_adjust(hspace=0.5)
plt.show()

# 相关性分析
# 将选定的列转换为数值类型，忽略转换错误
matrix = df[['Total Duration (hh:mm:ss)', 'Charging Time (hh:mm:ss)', 'Energy (kWh)', 'GHG Savings (kg)', 'Gasoline Savings (gallons)']].apply(pd.to_numeric, errors='coerce')
# 计算相关性矩阵
print(matrix.corr(method='pearson'))

# 将相关性矩阵保存到文件
with open('corr_matrix.txt', 'w') as fp:
    fp.write(str(matrix.corr(method='pearson')))

# 关联性分析
# 定义特征和目标变量
features = ['Total Duration (hh:mm:ss)', 'Charging Time (hh:mm:ss)', 'Energy (kWh)', 'GHG Savings (kg)', 'Gasoline Savings (gallons)']
target = 'Fee'

# 将时间格式的特征转换为数值类型（小时）
for feature in features[:2]:
    df[feature] = pd.to_timedelta(df[feature]).dt.total_seconds() / 3600

# 删除包含缺失值的行
df.dropna(subset=features + [target], inplace=True)

# 定义特征矩阵X和目标变量y
X = df[features]
y = df[target]

# 创建并训练决策树回归模型
tree_model = DecisionTreeRegressor(max_depth=3, random_state=42)
tree_model.fit(X, y)

# 可视化决策树
plt.figure(figsize=(20, 10))
plot_tree(tree_model, feature_names=X.columns, filled=True)
plt.title('Decision Tree for Fee Prediction')
plt.savefig('Decision_Tree.png')
plt.show()